package cn.net.dckj.common.utils.file;

import cn.net.dckj.common.config.Global;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;

/**
 * 文件处理工具类
 *
 * @author dckj
 */
public class FileUtils {
    public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";

    /**
     * 输出指定文件的byte数组
     *
     * @param filePath 文件路径
     * @param os       输出流
     * @return
     */
    public static void writeBytes(String filePath, OutputStream os) throws IOException {
        FileInputStream fis = null;
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                throw new FileNotFoundException(filePath);
            }
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0) {
                os.write(b, 0, length);
            }
        } catch (IOException e) {
            throw e;
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    /**
     * 删除文件
     *
     * @param filePath 文件
     * @return
     */
    public static boolean deleteFile(String filePath) {
        boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    /**
     * 文件名称验证
     *
     * @param filename 文件名称
     * @return true 正常 false 非法
     */
    public static boolean isValidFilename(String filename) {
        return filename.matches(FILENAME_PATTERN);
    }

    /**
     * 下载文件名重新编码
     *
     * @param request  请求对象
     * @param fileName 文件名
     * @return 编码后的文件名
     */
    public static String setFileDownloadHeader(HttpServletRequest request, String fileName)
            throws UnsupportedEncodingException {
        final String agent = request.getHeader("USER-AGENT");
        String filename = fileName;
        if (agent.contains("MSIE")) {
            // IE浏览器
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+", " ");
        } else if (agent.contains("Firefox")) {
            // 火狐浏览器
            filename = new String(fileName.getBytes(), "ISO8859-1");
        } else if (agent.contains("Chrome")) {
            // google浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        } else {
            // 其它浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }

    /**
     * 获取下载文件绝对路径
     *
     * @param filename 文件名称
     */
    public static String getAbsDownloadPath(String filename) {
        String downloadPath = Global.getDownloadPath() + "/" + filename;
        File desc = new File(downloadPath);
        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        return downloadPath;
    }

    /**
     * html 转word
     *
     * @param templateName
     * @param replaceData
     * @return
     * @Discription 只是把.html 转成.doc
     */
    public static String htmlToWord(String templateName, Map<String, String> replaceData) {
        String fileName = "";
        try {
            // 读取模板文件
            String templatesPath = "template/" + templateName;
            Resource resource = new ClassPathResource(templatesPath);
//            FileInputStream fileinputstream = (FileInputStream) resource.getInputStream();
            InputStream inputStream = resource.getInputStream();

            int lenght = inputStream.available();
            byte bytes[] = new byte[lenght];
            inputStream.read(bytes);
            inputStream.close();
            // 替换模板内容
            String templateContent = new String(bytes);
            for (Map.Entry<String, String> entry : replaceData.entrySet()) {
                //把模板页面上的 {{text}} 替换成 title 里的内容
                templateContent = templateContent.replaceAll("\\{\\{" + entry.getKey() + "\\}\\}", entry.getValue());
            }
            // 生成转换文件
            fileName = FileUploadUtils.changeFilename(templateName);
            fileName = fileName.split("\\.")[0] + ".doc";
            // 生成的html文件保存路径
            String filePathName = getAbsDownloadPath(fileName);
            // 建立文件输出流
            FileOutputStream fileoutputstream = new FileOutputStream(filePathName);
            byte tag_bytes[] = templateContent.getBytes();
            fileoutputstream.write(tag_bytes);
            fileoutputstream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileName;
    }

    /**
     * 生成文件
     *
     * @param baseDir
     * @param fileName 路径
     * @param content  内容
     */
    public static void writeInFileByfi(String baseDir, String fileName, String content) {
        File f = new File(baseDir + fileName);
        File fd = new File(baseDir);
        FileOutputStream fos = null;
        try {
            if (!fd.exists()) {
                fd.mkdirs();
            }
            if (!f.exists()) {
                f.createNewFile();
            }
            fos = new FileOutputStream(f);
            fos.write(content.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
